package com.easy_helth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy_helth.dto.DishDto;
import com.easy_helth.entity.Dish;
import com.easy_helth.entity.DishFlavor;
import com.easy_helth.mapper.DishMapper;
import com.easy_helth.service.DishFlavorService;
import com.easy_helth.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Transactional
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    DishFlavorService dishFlavorService;
//    新增菜品，同时保存口味
    @Override
    public void saveWithFlavor(DishDto dishDto) {
//        保存基本口味
        this.save(dishDto);
//        保存菜品口味数据

//        获取当前菜品id
        int dishId = dishDto.getId();

        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
//        保存菜品口味
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(int id) {
//        查询基本菜品
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
//        拷贝
        BeanUtils.copyProperties(dish,dishDto);
//        查询口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    @Override
    @Transactional
    public void  updateWithFlavor(DishDto dishDto) {
//        更新dish
        this.updateById(dishDto);
//        清理当前菜对应口味数据--dish_flavor中delete
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());

        dishFlavorService.remove(queryWrapper);

//        添加当前提交过来的口味数据--dish_flavor中insert操作

        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

    }

//    统计菜系点击数量
    @Override
    public Map<String, Integer> getDishNumber() {
        return null;
    }
}
